package cn.luowenjie.faceclock.adapter;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.chauthai.swipereveallayout.ViewBinderHelper;

import java.util.Calendar;
import java.util.List;
import cn.luowenjie.faceclock.R;
import cn.luowenjie.faceclock.clock.Clock;
import cn.luowenjie.faceclock.clock.FaceActivity;
import cn.luowenjie.faceclock.clock.SetClockActivity;
import cn.luowenjie.faceclock.database.DatabaseHelper;

import static android.content.Context.ALARM_SERVICE;
import static android.content.Context.MODE_PRIVATE;

public class RecyclerAdapter extends RecyclerView.Adapter {
    private List<Clock> mDataSet;
    private LayoutInflater mInflater;
    private Context mContext;
    DatabaseHelper databaseHelper;
    SQLiteDatabase db;
    private final ViewBinderHelper binderHelper = new ViewBinderHelper();


    public RecyclerAdapter(Context context, List<Clock> dataSet) {
        mContext = context;
        databaseHelper = new DatabaseHelper(mContext,"faceclock",null,1);
        db = databaseHelper.getWritableDatabase();
        mDataSet = dataSet;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.clock_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
        final ViewHolder holder = (ViewHolder) h;

        if (mDataSet != null && 0 <= position && position < mDataSet.size()) {
            final int hour = mDataSet.get(position).getHour();
            final int minute = mDataSet.get(position).getMinute();
            final String tag = mDataSet.get(position).getTag();
            final boolean state = mDataSet.get(position).getState();
            final int id = mDataSet.get(position).getId();
            String time;
            if(hour<10) {
                time = "0"+hour+":";
            }else { time = hour+":";}
            if(minute<10) { time = time+"0"+minute;}
            else {time = time+minute;}
            final String repeat;
            switch (mDataSet.get(position).getRepeat()){
                case 0:
                    repeat = "重复";
                    break;
                case 1:
                    repeat = "星期一";
                    break;
                case 2:
                    repeat = "星期二";
                    break;
                case 3:
                    repeat = "星期三";
                    break;
                case 4:
                    repeat = "星期四";
                    break;
                case 5:
                    repeat = "星期五";
                    break;
                case 6:
                    repeat = "星期六";
                    break;
                case 7:
                    repeat = "星期日";
                    break;
                default:
                    repeat = "重复";
                    break;
            }

            // Use ViewBindHelper to restore and save the open/close state of the SwipeRevealView
            // put an unique string id as value, can be any string which uniquely define the data
            binderHelper.bind(holder.swipeLayout, "555");

            // Bind your data here
            holder.bind(id, time, tag, state, repeat);
        }
    }

    @Override
    public int getItemCount() {
        if (mDataSet == null)
            return 0;
        return mDataSet.size();
    }


    public void saveStates(Bundle outState) {
        binderHelper.saveStates(outState);
    }


    public void restoreStates(Bundle inState) {
        binderHelper.restoreStates(inState);
    }

    private class ViewHolder extends RecyclerView.ViewHolder {
        private SwipeRevealLayout swipeLayout;
        private View frontLayout;
        private View deleteLayout;
        private Switch mSwitch;
        private TextView textView, textView2;

        public ViewHolder(View itemView) {
            super(itemView);
            swipeLayout = (SwipeRevealLayout) itemView.findViewById(R.id.swipe_layout);
            frontLayout = itemView.findViewById(R.id.front_layout);
            deleteLayout = itemView.findViewById(R.id.delete_layout);
            mSwitch = itemView.findViewById(R.id.mswitch);
            textView = (TextView) itemView.findViewById(R.id.tv_time);
            textView2 = (TextView) itemView.findViewById(R.id.tv_repeat);

        }

        public void bind(final int id, final String time, final String tag, boolean state, final String repeat) {
            deleteLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    db.delete("clocks","_id=?",new String[]{String.valueOf(id)});
                    mDataSet.remove(getAdapterPosition());
                    notifyItemRemoved(getAdapterPosition());
                }
            });

            textView.setText(time);
            if(repeat!=""){
                textView2.setText(tag+",  "+repeat);
            }
            else {
                textView2.setText(tag);
            }
            frontLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, SetClockActivity.class);
                    intent.putExtra("position", getAdapterPosition());
                    intent.putExtra("mode", "edit");
                    mContext.startActivity(intent);
                }
            });

            //mSwitch.setChecked(state);
            mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(ALARM_SERVICE);
                    Intent intent = new Intent(mContext, FaceActivity.class);
                    PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
                    Calendar c = Calendar.getInstance();
                    c.setTimeInMillis(System.currentTimeMillis());
                    if(buttonView.isChecked()) {
                        mDataSet.get(getAdapterPosition()).setState(true);
                        c.setTimeInMillis(System.currentTimeMillis());
                        // 根据用户选择的时间来设置Calendar对象
                        c.set(Calendar.HOUR, mDataSet.get(getAdapterPosition()).getHour());
                        c.set(Calendar.MINUTE, mDataSet.get(getAdapterPosition()).getMinute());
                        alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);

                    }
                    else {
                        //mDataSet.get(getAdapterPosition()).setState(false);
                        //alarmManager.cancel(pi);
                    }
                }
            });
        }
    }
}